package com.jiunuan.live.core.server.handler.tcp;

import com.jiunuan.live.core.server.common.ChannelHandlerContextCache;
import com.jiunuan.live.core.server.common.ImContextUtils;
import com.jiunuan.live.core.server.common.ImMsg;
import com.jiunuan.live.core.server.handler.ImHandlerFactory;
import com.jiunuan.live.framework.redis.starter.key.IMCoreServerProviderCacheKeyBuilder;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @Author: JiuNuan
 * @CreateTime: 2024-08-10 21:36
 * @Description: handler
 */

@Component
@ChannelHandler.Sharable
public class TcpImServerCoreHandler extends SimpleChannelInboundHandler {
    @Resource
    private ImHandlerFactory imHandlerFactory;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private IMCoreServerProviderCacheKeyBuilder cacheKeyBuilder;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 对消息体类型进行判断
        if(!(msg instanceof ImMsg)){
            throw new IllegalArgumentException("[TcpImServerCoreHandler] error msg,msg is:" + msg);
        }
        ImMsg imMsg = (ImMsg)msg;
        // 根据code类型分发给不同handler
        imHandlerFactory.doMsgHandler(ctx, imMsg);
    }

    /**
     * 正常或意外断线都会触发到此
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Long userId = ImContextUtils.getUserId(ctx);
        Integer appId = ImContextUtils.getAppId(ctx);
        if(userId != null && appId != null){
            ChannelHandlerContextCache.remove(userId);
            // 移除用户之前存在的ip记录
            redisTemplate.delete(cacheKeyBuilder.buildIMBindIpKey(appId, userId));
        }
    }
}
